<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Camera Capture</title>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width="640" height="480"></canvas>
<img id="photo" alt="The captured image will appear in this box.">

<script type="module">
    const getCameraStream = async () => {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            return navigator.mediaDevices.getUserMedia({
                video: {
                    facingMode: 'environment',
                    width: 3840,
                    height: 2160,
                },
                audio: false,
            });
        } else {
            return Promise.reject(new Error('设备不支持开启摄像头'));
        }
    };

    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const photo = document.getElementById('photo');
    const captureButton = document.getElementById('capture');

    // 获取摄像头视频流
    try {
        const stream = await getCameraStream()
        video.playsInline = true;
        video.autoplay = true;
        video.srcObject = stream;
    } catch (err) {
        console.error('Error accessing the camera.', err);
    }

    // 捕捉按钮点击事件
    captureButton.addEventListener('click', () => {
        // 使用 canvas 截图
        const context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 将截图转换为图像 URL
        const dataURL = canvas.toDataURL('image/png');
        // 显示截图
        photo.src = dataURL;
    });
</script>
</body>
</html>
